package jp.nyatla.nsdb;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;

import javax.servlet.jsp.JspWriter;

public class NtgUtil
{
	public static final int CT_PSP     = 0;
	public static final int CT_IPAD    = 1;
	public static final int CT_FIREFOX = 2;	
	/**
	 * ユーザエージェントからクライアントタイプを返す
	 * @param i_user_agent
	 * @return
	 */
	public static int getClientType(String i_user_agent)
	{
		if(i_user_agent!=null){
			if(i_user_agent.indexOf("PSP")>=0){
				return CT_PSP;
			}
			if(i_user_agent.indexOf("iPad")>=0){
				return CT_IPAD;
			}
		}
		return CT_FIREFOX;
	}
	private static char[] _buf=new char[1024];
	public synchronized static void insertFile(String i_uri,JspWriter o_out) throws IOException
	{
		FileInputStream in = new FileInputStream(i_uri);
		InputStreamReader in2 = new InputStreamReader(in, "UTF-8");

	    try {
	        int contents;
	        while ((contents =in2.read(_buf)) != -1){
	        	o_out.write(_buf,0,contents);
	        }
	    }finally{
	    	in2.close();
	    	in.close();
	    }
	}
	public static String formatNow()
	{
		Calendar cal1 = Calendar.getInstance();
	    int month = cal1.get(Calendar.MONTH) + 1;  //(3)現在の月を取得
	    int day = cal1.get(Calendar.DATE);         //(4)現在の日を取得
	    int hour = cal1.get(Calendar.HOUR_OF_DAY); //(5)現在の時を取得
	    int minute = cal1.get(Calendar.MINUTE);    //(6)現在の分を取得
	    int second = cal1.get(Calendar.SECOND);    //(7)現在の秒を取得
	    return month+"/"+day+" "+hour+":"+minute+":"+second;
	}

	public static String formatTime(long time)
	{
		long h=time/1000;
		int s=(int)(h%60);
		h/=60;
		int m=(int)(h%60);		
		h/=60;
		return (h>0?(h+"時間"):"")+(m>0?(m+"分"):"")+(s>0?(s+"秒"):"0秒");
	}
	public static String escapeJson(String i_str)
	{
		return i_str.replace('\n',' ').replace("\"","\\\"").replaceAll("<","&lt;");
	}
	/**
	 * i_textが、i_screen_name宛の物であるかを返します。
	 * @param i_text
	 * @param i_screen_name
	 * @return
	 */
	public static boolean hasMySName(String i_text,String i_screen_name)
	{
		int idx=i_text.indexOf(i_screen_name);
		if(idx<1){
			return false;
		}
		if(i_text.charAt(idx-1)!='@'){
			return false;
		}
		int l=i_screen_name.length();
		if(idx+l>=i_text.length()){
			return true;
		}
		char t=i_text.charAt(idx+l);
		if(Character.isLowerCase(t) || Character.isUpperCase(t) || Character.isDigit(t) || t=='_'){
			return false;
		}
		return true;
	}
	
	
}
